package com.sinsz.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.sinsz.nacos.listener.Cache;
import com.sinsz.nacos.listener.NacosListener;
import com.sinsz.nacos.properties.NacosProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 配置中心配置入口
 *
 * @author chenjianbo
 */
@Configuration
@EnableConfigurationProperties(value = {NacosProperties.class})
@ComponentScan(value = "com.sinsz.nacos")
public class NacosAutoConfiguration implements ApplicationContextAware, CommandLineRunner {

    private final NacosProperties properties;

    private static final Logger logger = LoggerFactory.getLogger(NacosAutoConfiguration.class);

    @Autowired
    public NacosAutoConfiguration(NacosProperties properties) {
        this.properties = properties;
    }

    /**
     * 获取容器上下文
     * @param context
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(@NonNull ApplicationContext context) throws BeansException {
        Cache.setContext(context);
    }

    /**
     * 执行配置服务注册
     *
     * @return
     */
    @Override
    public void run(String... args) {
        if (!properties.isEnable()) {
            logger.warn("未开启配置中心模式");
            return ;
        }
        final String address = StringUtils.isEmpty(properties.getAddress()) ? "127.0.0.1:8848" : properties
                .getAddress();
        final long timeout = properties.getTimeout() <= 0 ? 5000 : properties.getTimeout();
        Map<String, List<String>> config = properties.getConfig();
        if (config == null || config.isEmpty()) {
            logger.warn("未能获取到配置信息");
            return ;
        }
        try {
            for (Map.Entry<String, List<String>> entry : config.entrySet()) {
                final String group = entry.getKey();
                List<String> dataIds = entry.getValue();
                if (dataIds != null && !dataIds.isEmpty()) {
                    for (String dataId : dataIds) {
                        Properties properties = new Properties();
                        properties.put(PropertyKeyConst.SERVER_ADDR, address);
                        ConfigService service = NacosFactory.createConfigService(properties);
                        service.getConfig(dataId, group, timeout);
                        String status = service.getServerStatus();
                        if (StringUtils.isEmpty(status) || !"UP".equals(status)) {
                            logger.error(">>>>>>>>>> nacos Status: {}", service.getServerStatus());
                            return ;
                        }
                        service.addListener(dataId, group, new NacosListener());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}